package com.xiaoyu.lanling.feature.ontv.data

import `in`.srain.cube.request.FailData
import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModel
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.ontv.TVListEvent
import com.xiaoyu.lanling.event.ontv.TVLogger
import com.xiaoyu.lanling.feature.fate.model.TvFlipItem

class TVData(numPerPage: Int) : PagedListDataModel<TvFlipItem>(numPerPage) {
    private val requestTag = Any()

    override fun doQueryData() {
        TVLogger.logRequestStart()
        RequestCreator.create<TVListEvent>(TVListEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_ONTV_LIST)
                .appendQueryDataTo(listPageInfo)
                .setRequestHandler(object : RequestDefaultHandler<TVListEvent, JsonData>() {
                    override fun processOriginData(originData: JsonData): TVListEvent {
                        val data = originData.optJson("data")
                        val list = ListUtil.convertToList(data.optJson("list").toList()) { TvFlipItem(it) }
                        updateResult(data, list)
                        TVLogger.logRequestSuccess()
                        return TVListEvent(requestTag, list)
                    }

                    override fun onRequestFail(failData: FailData?) {
                        super.onRequestFail(failData)
                        TVLogger.logRequestFail()
                    }

                    override fun onRequestFinish(event: TVListEvent?) {
                        event?.post()
                    }
                })
                .enqueue()
    }
}